from django.shortcuts import render

# Create your views here.
from rest_framework import mixins, filters, permissions
from rest_framework import generics

from .filters import MatchFilter
from .models import Match, Team
from .serializers import MatchListSerializer, MatchDetailSerializer, TeamListSerializer
from .pagination import MyPageNumberPagination


class MatchList(mixins.ListModelMixin,
                mixins.CreateModelMixin,
                generics.GenericAPIView):  # GenericAPIView 要继承在最后，
    pagination_class = MyPageNumberPagination
    filter_class = MatchFilter
    queryset = Match.objects.all()
    serializer_class = MatchListSerializer

    filter_backends = (filters.OrderingFilter,)
    ordering_fields = ('views',)

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):  # post方法接受用户发过来的请求数据后，有时只需转发不需要创建模式对象实例，所以post方法不能简单等于create方法
        return self.create(request, *args, **kwargs)

    # 将request.user与author绑定。调用create方法时执行如下函数。通过看源码就可以看出来了 [钩子函数], 当我们创建对象的时候会执行的方法
    def perform_create(self, serializer):
        serializer.save(author=self.request.user)


# 莫岳恒

class MatchDetail(mixins.RetrieveModelMixin,
                  mixins.UpdateModelMixin,
                  mixins.DestroyModelMixin,
                  generics.GenericAPIView):
    # 这是GenericAPIView才可以指定数据集和查询集
    queryset = Match.objects.all()
    serializer_class = MatchDetailSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

class TeamList(mixins.ListModelMixin,
                mixins.CreateModelMixin,
                generics.GenericAPIView):  # GenericAPIView 要继承在最后，

    permission_classes = (permissions.IsAuthenticated,)
    # filter_class = MatchFilter
    queryset = Team.objects.all()
    serializer_class = TeamListSerializer

    # filter_backends = (filters.OrderingFilter,)
    # ordering_fields = ('views',)

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):  # post方法接受用户发过来的请求数据后，有时只需转发不需要创建模式对象实例，所以post方法不能简单等于create方法
        return self.create(request, *args, **kwargs)

    # 将request.user与author绑定。调用create方法时执行如下函数。通过看源码就可以看出来了 [钩子函数], 当我们创建对象的时候会执行的方法
    def perform_create(self, serializer):
        serializer.save(leader=self.request.user.profile)